package com.yanx.common.result;

public interface IResult<T> {

    Integer SUCCESS_CODE = 0;
    String SUCCESS_MSG = "success";

    void init(int code, String msg);

    default void initData(T data) {
    }

    default void initPaging() {
    }

    /**
     * 自定义返回封装类
     */
    ThreadLocal<Class<? extends IResult>> RESULT_CLASS = ThreadLocal.withInitial(() -> null);

    static void setResultClass(Class<? extends IResult> resultCLass) {
        RESULT_CLASS.set(resultCLass);
    }

    static IResult build(Class<? extends IResult> clazz, boolean isPage) {
        IResult result;
        if (clazz == null) {
            clazz = RESULT_CLASS.get();
            RESULT_CLASS.remove();
        }
        if (clazz != null && clazz != Result.class) {
            try {
                result = clazz.newInstance();
            } catch (InstantiationException e) {
                throw new RuntimeException("create result error!");
            } catch (IllegalAccessException e) {
                throw new RuntimeException("create result error!");
            }
        } else if (isPage) {
            result = new PageResult();
        } else {
            result = new Result();
        }
        return result;
    }
}
